<?php
header('Content-Type: application/json; charset=utf-8');
$logfile = $_SERVER["DOCUMENT_ROOT"]."/../runtime/log/statistics_install_menu.log";
file_put_contents($logfile, date('Y-m-d H:i:s')." assign_stats_rights start\n", FILE_APPEND);
try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=dev002_gxyusheng;charset=utf8mb4', 'root', '159456', [
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    $prefix = 'fa_';
    $menu = [
        ['name' => 'statistics/statistics/index', 'title' => '数据统计', 'icon' => 'fa fa-bar-chart', 'ismenu' => 1],
        ['name' => 'statistics/statistics/add', 'title' => '添加', 'ismenu' => 0],
        ['name' => 'statistics/statistics/edit', 'title' => '编辑', 'ismenu' => 0],
        ['name' => 'statistics/statistics/del', 'title' => '删除', 'ismenu' => 0],
        ['name' => 'statistics/statistics/multi', 'title' => '批量更新', 'ismenu' => 0],
        ['name' => 'statistics/statistics/recyclebin', 'title' => '回收站', 'ismenu' => 0],
        ['name' => 'statistics/statistics/restore', 'title' => '还原', 'ismenu' => 0],
        ['name' => 'statistics/statistics/import', 'title' => '导入', 'ismenu' => 0],
        ['name' => 'statistics/statistics/export', 'title' => '导出', 'ismenu' => 0],
    ];
    foreach ($menu as $item) {
        $stmt = $pdo->prepare("SELECT id,icon,ismenu FROM {$prefix}auth_rule WHERE name = ? LIMIT 1");
        $stmt->execute([$item['name']]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            $stmt2 = $pdo->prepare("INSERT INTO {$prefix}auth_rule (`pid`,`name`,`title`,`icon`,`condition`,`ismenu`,`status`,`weigh`,`createtime`,`updatetime`) VALUES (0,?,?,?,?,?,1,100,?,?)");
            $stmt2->execute([
                $item['name'],
                $item['title'],
                isset($item['icon']) ? $item['icon'] : '',
                '',
                $item['ismenu'],
                time(),
                time()
            ]);
        } else {
            $stmt2 = $pdo->prepare("UPDATE {$prefix}auth_rule SET `title` = ?, `icon` = ?, `ismenu` = ?, `updatetime` = ? WHERE `id` = ?");
            $stmt2->execute([
                $item['title'],
                isset($item['icon']) ? $item['icon'] : $row['icon'],
                $item['ismenu'],
                time(),
                $row['id']
            ]);
        }
    }
    $stmt = $pdo->prepare("SELECT id FROM {$prefix}auth_rule WHERE name = ? LIMIT 1");
    $stmt->execute(['statistics/statistics/index']);
    $indexRule = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($indexRule) {
        $childNames = [
            'statistics/statistics/add','statistics/statistics/edit','statistics/statistics/del','statistics/statistics/multi','statistics/statistics/recyclebin','statistics/statistics/restore','statistics/statistics/import','statistics/statistics/export'
        ];
        $in = implode(',', array_fill(0, count($childNames), '?'));
        $sql = "UPDATE {$prefix}auth_rule SET `pid` = ?, `updatetime` = ? WHERE `name` IN ($in)";
        $params = array_merge([$indexRule['id'], time()], $childNames);
        $pdo->prepare($sql)->execute($params);
        $ids = [];
        $stmt = $pdo->prepare("SELECT id FROM {$prefix}auth_rule WHERE name LIKE 'statistics/statistics/%'");
        $stmt->execute();
        while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) { $ids[] = $r['id']; }
        foreach ([2,3] as $gid) {
            $g = $pdo->prepare("SELECT id,rules FROM {$prefix}auth_group WHERE id = ? LIMIT 1");
            $g->execute([$gid]);
            $group = $g->fetch(PDO::FETCH_ASSOC);
            if ($group) {
                $set = [];
                if (!empty($group['rules'])) { $set = array_filter(explode(',', $group['rules'])); }
                $set = array_unique(array_merge($set, $ids));
                $pdo->prepare("UPDATE {$prefix}auth_group SET rules = ?, updatetime = ? WHERE id = ?")->execute([implode(',', $set), time(), $gid]);
            }
        }
    }
    file_put_contents($logfile, date('Y-m-d H:i:s')." assign_stats_rights done\n", FILE_APPEND);
    echo json_encode(['code' => 200, 'msg' => 'OK']);
} catch (Exception $e) {
    echo json_encode(['code' => 0, 'msg' => $e->getMessage()]);
}